//
//  CommonUtils.m
//  KKSDK
//
//  Created by jay Win on 2019/6/28.
//  Copyright © 2019 jay Win. All rights reserved.
//

#import "CommonUtils.h"

static CommonUtils *sharedInstance = nil;
@interface CommonUtils()<MFMailComposeViewControllerDelegate>

@property (nonatomic, strong) NSURL *assetURL;

@end

@implementation CommonUtils

+ (CommonUtils *)sharedManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[CommonUtils alloc] init];
    });
    return sharedInstance;
}
+ (void)vibrator:(int)type{
    if(IS_IPHONE_5||IS_IPHONE_4_OR_LESS||IS_IPHONE_6||IS_IPHONE_6P){
       
    }else{
        if(@available(iOS 10.0, *))
        {
            UIImpactFeedbackGenerator *feedBackGenertor = [[UIImpactFeedbackGenerator alloc]initWithStyle:UIImpactFeedbackStyleLight];
            if(type==1)
            {
                feedBackGenertor = [[UIImpactFeedbackGenerator alloc]initWithStyle:UIImpactFeedbackStyleMedium];
            }
            else
            {
                feedBackGenertor = [[UIImpactFeedbackGenerator alloc]initWithStyle:UIImpactFeedbackStyleHeavy];
            }
            [feedBackGenertor prepare];
            [feedBackGenertor impactOccurred];
        }
        else
        {
            AudioServicesPlaySystemSound(1519);
        }
    }
}

+ (void)sendEmail:(NSString *)recipients title:(NSString *)subject productName:(NSString *)disPlayName{
    if ([MFMailComposeViewController canSendMail]) {
        UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        SendMailViewController *vc = [[SendMailViewController alloc] init];
        [rootViewController presentViewController:vc animated:NO completion:^{}];
        [vc sendEmail:recipients title:subject productName:disPlayName];
    }else {
        NSString *recipients = @"mailto:subject=feedback@picfuntech.com";
        NSString *body = @"&body= ";
        NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
        email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
    }
}
    
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    [rootViewController dismissViewControllerAnimated:YES completion:nil];
}

+ (void)showCommentDialog{
    if(@available(iOS 10.3, *)) {
      [SKStoreReviewController requestReview];
    } else {

    }
}
+(void)copyStringToClipboard:(NSString *)content{
     UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
     [pasteBoard setString:content];
}
- (BOOL)hasInstallApp:(NSString *)urlSchemes{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlSchemes]]){
        return  YES;
    }else{
        return  NO;
    };
}
- (void)saveAssetWithPath:(NSString *)path ompletion:(void(^)(BOOL))completion {
    if (path) {
        NSURL *fileUrl = [NSURL fileURLWithPath:path];
        if (fileUrl) {
            ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
            if( [path hasSuffix:@".mov"]){
                [assetLibrary writeVideoAtPathToSavedPhotosAlbum:fileUrl completionBlock:^(NSURL *assetURL, NSError *error) {
                    if (!error) {
                        self->_assetURL = assetURL;
                        completion(YES);
                    }
                    else {
                        //handle error
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:[error localizedDescription] preferredStyle:UIAlertControllerStyleAlert];
                        //TODO: localize action title
                        UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                            
                        }];
                        [alert addAction:action];
                        UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
                        [rootViewController presentViewController:alert animated:YES completion:^{
                            
                        }];
                        completion(NO);
                    }
                }];
            }else{
                NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
                [assetLibrary writeImageDataToSavedPhotosAlbum:data metadata:NULL completionBlock:^(NSURL *assetURL, NSError *error) {
                    if (!error) {
                        self->_assetURL = assetURL;
                        completion(YES);
                    }
                    else {
                        //handle error
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:[error localizedDescription] preferredStyle:UIAlertControllerStyleAlert];
                        //TODO: localize action title
                        UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                            
                        }];
                        [alert addAction:action];
                        UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
                        [rootViewController presentViewController:alert animated:YES completion:^{
                            
                        }];
                        completion(NO);
                    }
                }];
            }
        }
    }
}
- (void)shareNative:(NSString *)filePath{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[fileURL] applicationActivities:nil];
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        UIPopoverController *popoverController = [[UIPopoverController alloc]initWithContentViewController:activityViewController];
        CGRect rect = CGRectMake(10, 100, 200, 200);
        [popoverController presentPopoverFromRect:rect inView:rootViewController.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    }
    else {
        [rootViewController presentViewController:activityViewController animated:YES completion:nil];
    }
}
- (void)shareToInstagram:(NSString *)filePath{
    [[CommonUtils sharedManager] saveAssetWithPath:filePath ompletion:^(BOOL) {
        if (![[CommonUtils sharedManager] hasInstallApp:@"instagram://app"]) {
            UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"share failed! Please intall instagram first." preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Close" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alertController addAction:cancelAction];
            [rootViewController presentViewController:alertController animated:YES completion:^{
                
            }];
            return;
        }
        NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@" =\"#%/:&<>?@\\^`{|}"];
        characterSet = [characterSet invertedSet];
        NSString *escapedString = [[CommonUtils sharedManager].assetURL.absoluteString stringByAddingPercentEncodingWithAllowedCharacters:characterSet];
        NSString *caption = @"";
        NSString *escapedCaption = [caption stringByAddingPercentEncodingWithAllowedCharacters:characterSet];
        NSURL *instagramURL = [NSURL URLWithString:[NSString stringWithFormat:@"instagram://library?AssetPath=%@&InstagramCaption=%@", escapedString, escapedCaption]];
        [[UIApplication sharedApplication] openURL:instagramURL];
    }];
}
- (void)saveToAlbum:(NSString *)filePath{
    [[CommonUtils sharedManager] saveAssetWithPath:filePath ompletion:^(BOOL) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"Video saved" preferredStyle:UIAlertControllerStyleAlert];
        //TODO: localize action title
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:action];
        UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        [rootViewController presentViewController:alert animated:YES completion:^{
            
        }];
    }];
    
}
+ (BOOL)checkAlbumPermission{
    BOOL isOpen;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
    PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
    isOpen = YES;
    if (authStatus == PHAuthorizationStatusRestricted || authStatus == PHAuthorizationStatusDenied) {
        isOpen = NO;
    }
#else
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    isOpen = YES;
    if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied) {
        isOpen = NO;
    }
#endif
    return isOpen;
}
-(void)requestAlbumPermission{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status == PHAuthorizationStatusAuthorized) {
            [self.delegate onRequestPermissionStateResponse:@"GRANTED_ALBUM"];
        }else{
            [self.delegate onRequestPermissionStateResponse:@"REFUSE_ALBUM"];
        }
    }];
}
+ (BOOL)checkCameraPermission{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusNotDetermined) {
        return NO;
    } else if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        return NO;
    } else {
        return YES;
    }
#endif
    
}
- (void)requestCameraPermission{
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        if (granted) {
            [self.delegate onRequestPermissionStateResponse:@"GRANTED_CAMERA"];
        }else{
            [self.delegate onRequestPermissionStateResponse:@"REFUSE_CAMERA"];
        }
    }];
}
+ (BOOL)isIphoneXAbove{
    return IPhoneX;
}
+ (NSString *)getLocale{
    return  [[NSLocale currentLocale]localeIdentifier];
}
+ (NSString *)getLanguage{
    return  [[NSLocale preferredLanguages]objectAtIndex:0];
}
+ (BOOL)isIPad{
    NSString *deviceType = [UIDevice currentDevice].model;
    if([deviceType isEqualToString:@"iPhone"]) {
        return NO;
    }
    else if([deviceType isEqualToString:@"iPod touch"]) {
        return NO;
    }
    else if([deviceType isEqualToString:@"iPad"]) {
        return YES;
    }
    return NO;
}
+ (BOOL)isSupportARKit{
    if (@available(iOS 11.0, *)) {
        if ([ARConfiguration isSupported]) {
            return YES;
        }
    }
    return NO;
}

+ (void)checkUpdateAppVersion:(NSString *)appStoreID title:(NSString *)titleText positive:(NSString *)positiveButtonText negative:(NSString *)negativeButtonText message:(NSString *)customMessage{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    NSString *appStoreUrl = [NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@",appStoreID];
    NSURL *url=[NSURL URLWithString:appStoreUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            NSArray *resultsArr =dict[@"results"];
            NSDictionary *info = [resultsArr lastObject];
            NSString *appStoreCurrentVersion = info[@"version"];
            NSString *appCurrentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
            if ([appCurrentVersion compare:appStoreCurrentVersion options:NSNumericSearch] == NSOrderedAscending){//有更新版本，需要提示前往更新
                NSString *message=@"";
                if([customMessage isEqualToString:@""]&&info[@"releaseNotes"]){
                    message=info[@"releaseNotes"];
                }else{
                    message=customMessage;
                }
                UIAlertController *alert =[UIAlertController alertControllerWithTitle:titleText message:message preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:negativeButtonText style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    //取消更新
                }]];
                [alert addAction:[UIAlertAction actionWithTitle:positiveButtonText style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/cn/app/id%@?mt=8",appStoreID]]];
                }]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [rootViewController presentViewController:alert animated:YES completion:^{
                        
                    }];
                });
                
            }else{//没有更新版本，不进行操作
                
            }
        }
    }];
    [dataTask resume];
}

@end
extern "C"{
    void Vibrator(int type){
        [CommonUtils vibrator:type];
    }
    void SendEMail( const char* recipients, const char* subject,const char* productName){
        [CommonUtils sendEmail:[NSString stringWithUTF8String:recipients] title:[NSString stringWithUTF8String:subject] productName:[NSString stringWithUTF8String:productName]];
    }
    void ShowSystemCommentDialog(){
        [CommonUtils showCommentDialog];
    }
    void CopyStringToClipboard(char *content){
        [CommonUtils copyStringToClipboard:[NSString stringWithUTF8String:content]];
    }
    bool HasInstallApp(char *urlSchemes){
        return [[CommonUtils sharedManager]hasInstallApp:[NSString stringWithUTF8String:urlSchemes]];
    }
    void ShareNative(char *path){
        [[CommonUtils sharedManager]shareNative:[NSString stringWithUTF8String:path]];
    }
    void SaveToAlbum(char *path){
        [[CommonUtils sharedManager]saveToAlbum:[NSString stringWithUTF8String:path]];
    }
    void ShareToInstagram(char *path){
        [[CommonUtils sharedManager]shareToInstagram:[NSString stringWithUTF8String:path]];
    }
    bool CheckCameraPermission(){
       return  [CommonUtils checkCameraPermission];
    }
    bool CheckAlbumPermission(){
        return   [CommonUtils checkAlbumPermission];
    }
    void RequestCameraPermission(){
        [[CommonUtils sharedManager]requestCameraPermission];
    }
    void RequestAlbumPermission(){
        [[CommonUtils sharedManager]requestAlbumPermission];
    }
    bool IsIphoneXAbove(){
        return [CommonUtils isIphoneXAbove];
    }
    const char *GetLanguage(){
        return [[CommonUtils getLanguage]UTF8String];
    }
    const char *GetLocale(){
        return [[CommonUtils getLocale]UTF8String];
    }
    bool IsIPad(){
        return [CommonUtils isIPad];
    }
    bool IsSurrpotARKit(){
        return [CommonUtils isSupportARKit];
    }
    void PopupUpdateNoticeDialog(char *appStoreID,char *title,char *positiveText,char *cancelText,char *customMessage){
        NSString *messageText=@"";
        if(customMessage){
            messageText=[NSString stringWithUTF8String:customMessage];
        }
        [CommonUtils checkUpdateAppVersion:[NSString stringWithUTF8String:appStoreID]
                                     title:[NSString stringWithUTF8String:title]
                                  positive:[NSString stringWithUTF8String:positiveText]
                                  negative:[NSString stringWithUTF8String:cancelText]
                                   message:messageText];
    }
}
